package com.ttbj.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ttbj.product.api.AppletUserFacade;
import com.ttbj.product.bean.dto.UserDto;
import com.ttbj.util.ResultUtil;
import com.ttbj.util.StringUtil;

 
/**
 * 验证openID拦截器
 * @author Medivh
 */
public class OpenIdCheckInterceptor extends HandlerInterceptorAdapter {
	public static final Logger LOGGER = LoggerFactory.getLogger(OpenIdCheckInterceptor.class);
	@Autowired
	AppletUserFacade appletUserFacade = null;
	public static final Logger logger = LoggerFactory.getLogger(OpenIdCheckInterceptor.class);
	private List<String> excludePaths = null;
	private String excludePath; // 匹配不拦截请求url
	public String getExcludePath() {
		return excludePath;
	}
	public void setExcludePath(String excludePath) {
		this.excludePath = excludePath;
	}

	@Override
	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getServletPath();//用户请求的url
		logger.info("验证openId拦截器");
		excludePaths = new ArrayList<String>();
		if (StringUtils.isNotEmpty(excludePath)) {
			String[] paths = excludePath.split(";");
			for (String p : paths) {
				if (!StringUtils.isEmpty(p)) {
					excludePaths.add(p.trim());
				}
			}
		}
		PathMatcher matcher = new AntPathMatcher();
		for (String str : excludePaths) {
			if (matcher.match(str, path)) {
				return super.preHandle(request, response, handler);
			}
		}
		/*用户验证信息*/
		Map<String, String[]> map = request.getParameterMap();
		//测试或空参函数通过excludePath配置
		if(null == map ||map.isEmpty() || !map.containsKey("openId")){
			ResultUtil.throwExcepion(ResultUtil.createFail("messages", 115, null),"openId不存在");
		}
		String openId = map.get("openId")[0];
		LOGGER.info("web拦截器验证openId,:{}", openId);
		if(StringUtil.isEmpty(openId)){
			ResultUtil.throwExcepion(ResultUtil.createFail("messages", 115, null),"openId为空");
		}
		UserDto user = appletUserFacade.getUser(new UserDto(openId));
		if (user == null) {
			ResultUtil.throwExcepion(ResultUtil.createFail("messages", 115, null),"openId未查询到用户信息");
			return false;
		}
		request.setAttribute("user", user);
		return super.preHandle(request, response, handler);
	}

}
